package com.xinxi11.project.qx.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.centfor.core.module.ConfigPropUtil;
import com.centfor.core.spring.SpringContextHolder;

/**
 * 如果当前无有效用户url会重定向到login.action页面
 */
public class EffectiveUserFilter implements Filter {

	private static final String loginAction = ConfigPropUtil.getProperty("cas_login_url");
	private static final String excludeRegex = ConfigPropUtil.getProperty(
			"url_dffectiveUser_exclude_regex", "/(login|logout)(.action|.jsp|.do)$");

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String uri = request.getRequestURI();
		Pattern pattern = Pattern.compile(excludeRegex);
		Matcher matcher = pattern.matcher(uri);
		boolean isExclude = matcher.matches();
		if (!isExclude) {
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			HttpSession session = httpServletRequest.getSession(false);
			Boolean isLogin = true;
			if (session == null) {
				isLogin = false;
			} else {
				String userCode = (String) session.getAttribute(SpringContextHolder.USER_LOGIN_ID);
				if (userCode == null || "".equals(userCode.trim())) {
					isLogin = false;
				}
			}
			if (!isLogin) {
				HttpServletResponse response = (HttpServletResponse) servletResponse;
				response.sendRedirect(loginAction);
				return;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
